from flask import Blueprint, render_template, request, current_app
import socket
from Crypto import Random
import StringIO

from .admin import rc4, login_required
from .db import get_db2

app = current_app

msg_push = Blueprint("msg_push", __name__)

random_fp = Random.new()

@msg_push.route("/push", methods=["GET","POST"])
@login_required
def push():

    if request.method == "GET":
        conn = get_db2()
        cur = conn.cursor()
        cur.execute("select username from location limit 200")
        res = cur.fetchall()
        cur.close()
        vendors = []
        users = []
        for r in res:
            u = str(r[0])
            v = u.split("_", 1)[0]
            if v not in vendors:
                vendors.append(v)
            users.append(u)
        return render_template("msg_push.html", vendors  = vendors, users = users)
    elif request.method == "POST":
        msg = request.form.get("msg", "")
        if not msg:
            return "no message entered"

        users=request.form.getlist("users")
        if not users:
            return "no users selected"

        app.logger.debug("send msg '%s' to '%s'" % (msg,str(users)))

        oks,fails=send_msg(msg, users)
        return render_template("push_status.html",msg = msg,success = oks, failed = fails)
    else:
        return "400 Bad Request",400

def send_msg(msg, users):
    key = "bd1146b4cfa503eb2c1056b693377f30"
    domain = "sip2.simicloud.com"
    port = 50600
    user = "POWER7_webmaster"
    METHOD='MESSAGE'
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.settimeout(5)
    text_tpl="""{method} sip:{to_user}@{domain} SIP/2.0\r\nVia: SIP/2.0/UDP 127.0.0.1;rport;branch=z9hG4bk{branch}\r\nFrom: <sip:{from_user}@{domain}>;tag={tag}\r\nTo: <sip:{to_user}@{domain}>\r\nCall-ID: {callid}\r\nMax-Forwards: 10\r\nContact: <sip:{from_user}@127.0.0.1>\r\nExpires: 20\r\nCSeq: {cseq} {method}\r\nAllow: OPTIONS,INFO,MESSAGE\r\nContent-Type: text/plain\r\nContent-Length: {clen}\r\nUser-Agent: pythonlib/2.7\r\n\r\n{msg}"""

    d = dict(
        method=METHOD,
        to_user="",
        from_user=user,
        domain=domain,
        tag=random_fp.read(10).encode("hex"),
        branch=random_fp.read(10).encode("hex"),
        callid=random_fp.read(5).encode("hex"),
        cseq=int(random_fp.read(1).encode("hex"),16),
        clen=len(msg),
        msg=msg
    )
    for u in users:
        d["to_user"] = u
        text=text_tpl.format(**d)
        #print "send msg to %s" % u
        sock.sendto(rc4(key,text),(domain,port))

    rs_msgs = []
    for i in range(len(users)):
        try:
            data,addr=sock.recvfrom(512)
        except:
            break
        rs_msgs.append(rc4(key,data))
    sock.close()
    oks = []
    fails = []
    for r in rs_msgs:
        fp = StringIO.StringIO(r)
        firstline = fp.readline()
        code = int(firstline.split(" ",2)[1])
        for u in users:
            if u in r:
                #print u,code
                if code == 200:
                    oks.append(u)
                else:
                    fails.append(u)
                break
    for u in users:
        if (u not in oks)  and (u not in fails):
            fails.append(u)
    return oks,fails
